package top.callback.inf.beautyleaf.server.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.callback.inf.beautyleaf.server.dao.PrefixDao;
import top.callback.inf.beautyleaf.server.entity.PrefixDO;
import top.callback.inf.beautyleaf.server.model.PrefixModel;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 前缀服务
 *
 * @author Pengyu Gan
 * CreateDate 2021/11/13
 */
@Slf4j
@Service
@Transactional(readOnly = true, rollbackFor = {Exception.class})
public class PrefixService {

    @Autowired
    private PrefixDao prefixDao;

    /**
     * 新增前缀
     * @param prefixModel {@link PrefixModel} 前缀信息
     * @return true 成功 false 失败
     */
    @Transactional
    public boolean addPrefix(PrefixModel prefixModel) {
        PrefixDO prefixDO = new PrefixDO();
        BeanUtils.copyProperties(prefixModel, prefixDO);
        return prefixDao.addPrefix(prefixDO) != 0;
    }

    /**
     * 编辑前缀
     * @param prefixModel {@link PrefixModel} 前缀信息
     * @return true 成功 false 失败
     */
    @Transactional
    public boolean editPrefix(PrefixModel prefixModel) {
        PrefixDO prefixDO = new PrefixDO();
        BeanUtils.copyProperties(prefixModel, prefixDO);
        return prefixDao.editPrefix(prefixDO) != 0;
    }

    /**
     * 删除前缀
     * @param EnvId 前缀 ID
     * @return true 成功 false 失败
     */
    @Transactional
    public boolean removePrefix(long EnvId) {
        return prefixDao.removePrefix(EnvId) != 0;
    }

    /**
     * 查询指定 ID 的前缀
     * @param EnvId 前缀 ID
     * @return {@link PrefixModel} 前缀信息
     */
    public PrefixModel findById(long EnvId) {
        PrefixDO prefixDO = prefixDao.findById(EnvId);
        if (null == prefixDO) {
            throw new RuntimeException("前缀不存在");
        }
        PrefixModel prefixModel = new PrefixModel();
        BeanUtils.copyProperties(prefixDO, prefixModel);
        return prefixModel;
    }

    /**
     * 查询所有前缀
     * @return 前缀列表
     */
    public List<PrefixModel> findAll() {
        List<PrefixDO> prefixSet = prefixDao.findAll();
        List<PrefixModel> prefixModels = new ArrayList<>();
        if (null != prefixSet && !prefixSet.isEmpty()) {
            prefixModels = prefixSet.stream().map(u -> {
                PrefixModel prefixModel = new PrefixModel();
                BeanUtils.copyProperties(u, prefixModel);
                return prefixModel;
            }).collect(Collectors.toList());
        }
        return prefixModels;
    }

}
